//
//  CTextField.m
//  Hipay_Business
//
//  Created by Mac on 16/7/1.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "CTextField.h"

@interface CTextField()
@property (nonatomic, strong) NSMutableArray *verfiyData;
@property (nonatomic, strong) NSString *separator;
@property (nonatomic) NSInteger splitcount;

@property (nonatomic) NSInteger maxLength;
@property (nonatomic, strong) void (^lenthchangeblock)(NSInteger);
@end

@implementation CTextField

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

- (instancetype)init{
    self = [super init];
    if (self) {
        [self initView];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initView];
    }
    return self;
}

- (void)initView{
    _verfiyData = [NSMutableArray array];
    __block typeof(self) blockself = self;
    [self setBk_shouldChangeCharactersInRangeWithReplacementStringBlock:^BOOL(UITextField *tfd, NSRange range, NSString *str) {
        if ([[[UITextInputMode currentInputMode]primaryLanguage] isEqualToString:@"emoji"]) {
            return NO;
        }
        NSString *newtext = [tfd.text stringByReplacingCharactersInRange:range withString:str];
        if (tfd.markedTextRange) {
            return YES;
        }
        BOOL shouldChange = YES;
        if (blockself.changeBlock) {
            blockself.changeBlock(newtext);
        }
        NSInteger maxLength = blockself.maxLength;
        if (blockself.inputType == CTextFieldInputTypePhone) {
            maxLength = 13;
        }
        if (maxLength > 0) {
            if (blockself.splitcount > 0) {
                maxLength = maxLength + maxLength / blockself.splitcount - (maxLength % blockself.splitcount == 0 ? 1 : 0);
            }
            shouldChange = newtext.length <= maxLength;
            if (!shouldChange) {
                return NO;
            }
        }
        if (blockself.inputType == CTextFieldInputTypePhone) {
            if ((range.location == 0 && (![@[@"", @"1"] containsObject:str])) ||
                (range.location == 1 && [@[@"0", @"1", @"2"] containsObject:str])) {
                shouldChange = NO;
            }
            if (shouldChange) {
                blockself.text = [blockself formatMobileSplit:newtext place:@" "];
            }
            shouldChange = NO;
        }
        if (blockself.splitcount > 0) {
            blockself.text = [blockself formatStringSplit:newtext count:blockself.splitcount place:@" "];
            shouldChange = NO;
        }
        if (blockself.inputType == CTextFieldInputTypeMoney) {
            NSString *newstr = [NSString stringWithFormat:@"%zd", [str integerValue]];
            if (![newstr isEqualToString:str] && ![str isEqualToString:@""] && ![str isEqualToString:@"."]) {
                tfd.text = newstr;
                return false;
            }
            shouldChange = NO;
            NSInteger start = [tfd.text rangeOfString:@"."].location;
            if ([newtext isEqualToString:@"."]) {
                [tfd setText:@"0"];
            } else if (start != NSNotFound && [str isEqualToString:@"."]) {
                shouldChange = NO;
            }else if (start == NSNotFound && [newtext hasPrefix:@"0"] && newtext.length > 1 && ![str isEqualToString:@"."]) {
                [tfd setText:[newtext stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@""]];
                shouldChange = NO;
            }else if (start == NSNotFound || start + 4 > newtext.length) {
                shouldChange = YES;
            }
            
        }
        if (blockself.inputType == CTextFieldInputTypeCardID) {
            NSString *temp = [tfd.text stringByReplacingCharactersInRange:range withString:str];
            shouldChange = YES;
            if (temp.length > 18) {
                shouldChange = false;
            }
            for (int i = 0; i < temp.length; i++) {
                int chat = [temp characterAtIndex:i];
                if (chat >= '0' && chat <= '9' && i <= 16) {
                    continue;
                }else if(i == 17 && ((chat >= '0' && chat <= '9') || (chat == 'x' || chat == 'X'))){
                    continue;
                }else{
                    shouldChange = false;
                }
            }
            
        }
        //        if(self.inputType & CTextFieldInputTypeNum) shouldChange = YES;
        return shouldChange;
    }];
    
    
    [self bk_addEventHandler:^(id sender) {
        if(!(self.inputType | CTextFieldInputTypeHanz)) return ;
        UITextPosition *position = [self positionFromPosition:[self markedTextRange] offset:0];
        if (position) {
            return;
        }
        NSInteger maxLength = self.maxLength;
        if (maxLength > 0) {
            if (self.splitcount > 0) {
                maxLength = maxLength + maxLength / self.splitcount - (maxLength % self.splitcount == 0 ? 1 : 0);
            }
            if (self.text.length > maxLength) {
                self.text = [self.text substringWithRange:NSMakeRange(0, maxLength)];
            }
        }
    } forControlEvents:UIControlEventEditingChanged];
    [self setFont:F(12)];
}

- (void)setFirstValue:(NSString *)firstValue{
    _firstValue = firstValue;
    if (self.inputType == CTextFieldInputTypePhone) {
        self.text = [self formatMobileSplit:firstValue place:@" "];
    }else{
        if (self.splitcount > 0) {
            self.text = [self formatStringSplit:firstValue count:self.splitcount place:@" "];
        }else{
            self.text = firstValue;
        }
    }
}

- (NSString *)value{
    NSString *v = self.text;
    if (self.splitcount > 0) {
        v = [v stringByReplacingOccurrencesOfString:self.separator withString:@""];
    }
    if (self.inputType == CTextFieldInputTypePhone) {
        v = [v stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    return v;
}

- (BOOL)resignFirstResponder{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    return [super resignFirstResponder];
}

- (BOOL)becomeFirstResponder{
    return [super becomeFirstResponder];
}

- (void)setInputType:(CTextFieldInputType)inputType{
    _inputType = inputType;
    if (inputType & CTextFieldInputTypePassword) {
        [self setSecureTextEntry:YES];
    }
    if (inputType & (CTextFieldInputTypeNum | CTextFieldInputTypePhone)) {
        [self setKeyboardType:UIKeyboardTypeNumberPad];
    }else if(inputType == CTextFieldInputTypeMoney){
        [self setKeyboardType:UIKeyboardTypeDecimalPad];
    }else if(inputType == CTextFieldInputTypeABC){
        [self setKeyboardType:UIKeyboardTypeASCIICapable];
    }else if(inputType & (CTextFieldInputTypeHanz | CTextFieldInputTypeDefault)){
        [self setKeyboardType:UIKeyboardTypeDefault];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:UITextFieldTextDidChangeNotification object:nil];
    }else if(inputType == CTextFieldInputTypeCardID){
        [self setKeyboardType:UIKeyboardTypeASCIICapable];
    }else{
        [self setKeyboardType:UIKeyboardTypeDefault];
    }
}

- (void) change:(NSNotification *)notif{
    [self cleanKey:self.text];
}

- (void) cleanKey:(NSString *)key{
    if (self.markedTextRange) { // 判断是否是输入中文
        return;
    }
    NSMutableString *str = [NSMutableString string];
    BOOL hasOther = false;
    for(int i=0; i< [key length];i++){
        int a = [key characterAtIndex:i];
        NSArray *b = @[@"·", @"×", @"—", @"‘", @"’", @"“", @"”", @"…", @"、", @"。", @"《", @"》", @"『", @"』", @"【", @"】", @"！", @"（", @"）", @"，", @"：", @"；", @"？"];
        NSString *word = [NSString stringWithFormat:@"%C", [key characterAtIndex:i]];
        if (_inputType == CTextFieldInputTypeDefault && (( a >= 0x4e00 && a <= 0x9fa5) || (a <= 128) || [b containsObject:word])) {
            [str appendString:word];
            continue;
        }
        if (_inputType & CTextFieldInputTypeHanz && ((a >= 0x4e00 && a <= 0x9fa5) || [b containsObject:word])) {
            [str appendString:word];
            continue;
        }
        if (_inputType & CTextFieldInputTypeNum && (a >= '0' && a <= '9')) {
            [str appendString:word];
            continue;
        }
        if (_inputType * CTextFieldInputTypeABC && ((a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z'))) {
            [str appendString:word];
            continue;
        }
        hasOther = true;
    }
    if (_changeBlock == nil) {
        return;
    }
    if (self.maxLength > 0 && str.length > self.maxLength) {
        self.changeBlock(str);
    }else if(hasOther == false){
        self.changeBlock(str);
        return;
    }else{
        [self setText:str];
    }   
    self.changeBlock(str);
}

- (void) setMaxLength:(NSInteger) length LengthChangeBlock:(void(^)(NSInteger))block{
    _maxLength = length;
    _lenthchangeblock = block;
}

- (void) setMinLength:(NSInteger) length msg:(NSString *)msg{
    [_verfiyData addObject:@{@"type":@"min", @"msg":msg ? msg : @"", @"len":[NSNumber numberWithInteger:length]}];
}

- (void) setPerSplitCount:(NSInteger) count separator:(NSString *)separator{
    _splitcount = count;
    _separator = separator;
}

- (BOOL)verfiy{
    if (self.value.length == 0) {
        [CClass showMessage:self.nullMsg ? self.nullMsg : self.placeholder];
        return false;
    }
    if (self.inputType == CTextFieldInputTypePhone && self.value.length != 11) {
        [CClass showMessage:@"请输入11位手机号"];
        return false;
    }
    for (NSDictionary *dic in _verfiyData) {
        if([dic[@"type"] isEqualToString:@"min"] && [dic[@"len"] integerValue] > self.value.length) {
            [CClass showMessage:dic[@"msg"]];
            return false;
        }
    }
    return true;
}

- (void)paste:(id)sender{
    if (_inputType == CTextFieldInputTypeNum) {
        return;
    }
    [super paste:sender];
}

- (NSString *) formatMobileSplit:(NSString *) str place:(NSString *)place{
    str = [str stringByReplacingOccurrencesOfString:place withString:@""];
    NSMutableString *temp = [NSMutableString string];
    NSInteger space = 3;
    for (int i = 0; i < str.length ; i += space) {
        if (i > 0) {
            space = 4;
        }
        if (i + space >= str.length) {
            [temp appendString:[str substringWithRange:NSMakeRange(i, str.length - i)]];
            break;
        }
        [temp appendString:[str substringWithRange:NSMakeRange(i, space)]];
        [temp appendString:place];
    }
    return temp;
}

- (NSString *) formatStringSplit:(NSString *) str count:(NSInteger)count place:(NSString *)place{
    str = [str stringByReplacingOccurrencesOfString:place withString:@""];
    NSMutableString *temp = [NSMutableString string];
    for (int i = 0; i < str.length ; i += count) {
        if (i + count >= str.length) {
            [temp appendString:[str substringWithRange:NSMakeRange(i, str.length - i)]];
            break;
        }
        [temp appendString:[str substringWithRange:NSMakeRange(i, count)]];
        [temp appendString:place];
    }
    return temp;
}

@end
